import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:geomancy/models/common_model.dart';
import 'package:geomancy/models/login_model.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/tools/http.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

class LoginAPI {
  ///获取登录验证码
  static Future<bool> getCode({required BuildContext context, required String phone}) async {
    try {
      final data = await Fetch.request(Method.GET, '/sms/getLoginCode', params: {
        "phone": phone
      }, context: context);
      final result = CommonModel.fromJson(json.decode(data.data));
      if (result.code == 200) {
        return true;
      }
      return false;
    } catch(e) {
      return true;
    }
  }
  ///验证码登录
  static Future<bool> loginWithCode({
    required BuildContext context,
    required String phone,
    required String code,
    required bool mounted
  }) async {
    try {
      final userProvider = context.read<UserProvider>();
      final data = await Fetch.request(Method.POST, '/user/loginWithCode', params: {
        "phone": phone,
        "code": code
      }, context: context);
      final result = LoginModel.fromJson(json.decode(data.data));
      if (result.code == 200 && mounted) {
        ///先存上token和userInfo
        userProvider.saveToken(result.data!.token.toString());
        userProvider.saveUserInfo(result.data!.user!);
        ///未注册
        if (result.data?.user?.username == null) {
          context.push('/register_nickname');
          return false;
        }
        if (result.data?.user?.sex == null) {
          context.push('/register_sex');
          return false;
        }
        if (result.data?.user?.birthday == null) {
          context.push('/register_birthday');
          return false;
        }
        return true;
      }
      if (result.message != null) {
        EasyLoading.showToast(result.message!);
      }
      return false;
    } catch(e) {
      return false;
    }
  }
}